package com.cloudspace.yunloan.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;


import com.cloudspace.yunloan.R;
import com.cloudspace.yunloan.YunloanApp;
import com.cloudspace.yunloan.ui.MyTitleBar;
import com.cloudspace.yunloan.ui.pulltorefresh.PullToRefreshWebView;
import com.cloudspace.yunloan.ui.pulltorefresh.base.PullToRefreshBase;
import com.cloudspace.yunloan.utils.AppUtil;
import com.cloudspace.yunloan.utils.MMAlert;
import com.cloudspace.yunloan.utils.ObjUtil;
import com.cloudspace.yunloan.utils.StringUtil;
import com.cloudspace.yunloan.utils.ToastMaker;

import java.lang.ref.WeakReference;


public class BrowserActivity extends YunloanActivity {
    private final static String INTENTURL = "intenturl";
    private final static int ADD_LODING_VIEW = 630;
    private final static int CANCEL_LODING_VIEW = 631;
    private final static int ERROR_CONTENT = 633;

    private final static int RECEIVE_AUTH_SUCCESS = 634;

    private final static String BUNDLE_EXTRA_AD = "bundle_extra_ad";


    private boolean errorNetWork = false;

    private PullToRefreshWebView mPullRefreshWebView;

    private WebView webpageView;
    private View mLoadingView = null;
    private View mEmptyView = null;


    private String url;
    private String second_url;

    private String mLastUrl;
    private String mLastTitle;

    private Dialog simpleAlertDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_browser, true);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        Bundle bundle = getIntent().getExtras();
        if (ObjUtil.isEmpty(bundle)) return;


        url = getIntent().getStringExtra(INTENTURL);
        second_url = getIntent().getStringExtra(BUNDLE_EXTRA_AD);

        initView();

        initWebView();

        updateContent(url);
    }

    private Handler mHandler = new SmallBrowserFragmentHandler(this);

    static class SmallBrowserFragmentHandler extends Handler {
        WeakReference<BrowserActivity> browserWeakReference;

        SmallBrowserFragmentHandler(BrowserActivity smallBrowserFragment) {
            browserWeakReference = new WeakReference<BrowserActivity>(smallBrowserFragment);
        }

        boolean isFinish() {
            return browserWeakReference == null || browserWeakReference.get() == null || browserWeakReference.get().isFinishing();
        }

        @Override
        public void handleMessage(Message msg) {
            final BrowserActivity browserActivity = browserWeakReference.get();
            if (isFinish())
                return;
            switch (msg.what) {
                case ADD_LODING_VIEW:
                    browserActivity.mLoadingView.setVisibility(View.VISIBLE);
                    browserActivity.mLoadingView.bringToFront();
                    break;
                case CANCEL_LODING_VIEW:
                    browserActivity.mLoadingView.setVisibility(View.GONE);
                    if (browserActivity.errorNetWork) {
                        browserActivity.mEmptyView.setBackgroundColor(browserActivity.getResources().getColor(R.color.base_txt_white3));
                        browserActivity.mEmptyView.setVisibility(View.VISIBLE);
                        TextView empty_tips = (TextView) browserActivity.mEmptyView.findViewById(R.id.empty_tips);
                        empty_tips.setText(browserActivity.getString(R.string.error_network_simple));
                        empty_tips.setVisibility(View.VISIBLE);
                        browserActivity.mEmptyView.bringToFront();
                    } else {
                        if (browserActivity.mEmptyView != null) {
                            browserActivity.mEmptyView.setVisibility(View.GONE);
                        }
                    }
                    browserActivity.mPullRefreshWebView.onRefreshComplete();
                    this.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            browserActivity.mPullRefreshWebView.getRefreshableView().scrollTo(0, 0);
                        }
                    }, 30);
                    break;
                case ERROR_CONTENT:
                    break;

                case RECEIVE_AUTH_SUCCESS:
                    browserActivity.authSuccess();
                    break;
                default:
                    break;
            }
        }


    }

    private void authSuccess() {
        if (webpageView != null){
            webpageView.reload();
        }
    }

    private void initWebView() {
        final WebSettings webseting = webpageView.getSettings();

        //设置浏览器标题
        webpageView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        if (webseting != null) {
            webseting.setJavaScriptEnabled(true);
            webseting.setJavaScriptCanOpenWindowsAutomatically(true);
            webseting.setBuiltInZoomControls(false);
            webseting.setSupportMultipleWindows(false);
            webseting.setSupportZoom(false);
            // 修改ua
            String ua = webseting.getUserAgentString();
            webseting.setUserAgentString(ua + " Yunloan/" + AppUtil.getAppVersionName());

            // enable Web Storage: localStorage
            webseting.setDomStorageEnabled(true);

            if (Build.VERSION.SDK_INT >= 21) { //5.0以上需要打开https/http混合显示
                webseting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
        }
        webpageView.requestFocus(View.FOCUS_DOWN);
        webpageView.clearView(); //设置浏览器访问,不同状态的行为
        setCacheEnable(true);

        //设置浏览器加载状态
        webpageView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                updateContent(url);
                return true;//true表示此事件在此处被处理，不需要再广播
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                                        String failingUrl) {
                if (errorCode == -2) {
                    ToastMaker.showToastShort(R.string.web_net_error);
                }
                mHandler.sendMessage(mHandler.obtainMessage(CANCEL_LODING_VIEW, description));
                errorNetWork = true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                updateTitleBar(webpageView.getTitle(), false);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    view.loadUrl("javascript:window.jsobj.getContent(setShareUrlParams())");
                }
                mHandler.sendMessage(mHandler.obtainMessage(CANCEL_LODING_VIEW, url));
            }

            @Override
            public void onLoadResource(WebView view, String url) {
//                //KTVLog.v(TAG, "onLoadResource : " + url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (url != null && url.contains("apk.7816480.com")) {
                    view.stopLoading();
                    mHandler.sendEmptyMessage(ERROR_CONTENT);
                } else {
                    mHandler.sendEmptyMessage(ADD_LODING_VIEW);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        //设置js弹出事件
        webpageView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mLastTitle = title;
                mLastUrl = url;
                updateTitleBar(title, false);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
                simpleAlertDialog = MMAlert.showAlert(BrowserActivity.this, message, "", getString(R.string.understand), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        result.confirm();
                    }
                });
                simpleAlertDialog.setCancelable(false);
                return true;
            }

            @Override
            public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,
                                                 WebStorage.QuotaUpdater quotaUpdater) {
                quotaUpdater.updateQuota(spaceNeeded * 2);
            }
        });

    }

    boolean appendparam = true;

    public void updateContent(final String url) {
        mLastUrl = url;
    }

    private String titleTxt;

    private void updateTitleBar(final String title, boolean forceUpdate) {
        if (!forceUpdate && (TextUtils.isEmpty(title) || title.equals(titleTxt))) {
            return;
        }

        if (!TextUtils.isEmpty(title)) {
            titleTxt = title;
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                MyTitleBar titleBar = getTitleBar();
                titleBar.getTitle().setSingleLine();
                titleBar.getTitle().setMaxWidth((int) YunloanApp.getInstance().getScreenWidth() * 8 / 10);
                titleBar.getTitle().setEllipsize(TextUtils.TruncateAt.END);

                titleBar.setSimpleMode(titleTxt);
                titleBar.getLeftView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }
        });
    }


    public void setCacheEnable(boolean flag) {
        try {
            if (flag) {
                webpageView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            } else {
                webpageView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                webpageView.clearCache(true);
//                HTTPFetcher.clearCookies(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void goBack() {
        if (webpageView.canGoBack()) {
            webpageView.goBack();
        }
    }

    private void initView() {
        mPullRefreshWebView = (PullToRefreshWebView) findViewById(R.id.webpageView);
        mPullRefreshWebView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        webpageView = mPullRefreshWebView.getRefreshableView();
        mLoadingView = findViewById(R.id.loadmore);
        mEmptyView = findViewById(R.id.empty_layout);
        mEmptyView.setBackgroundColor(getResources().getColor(R.color.base_txt_white3));
        mPullRefreshWebView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<WebView>() {
            @Override
            public void onRefresh(PullToRefreshBase<WebView> refreshView, PullToRefreshBase.Mode currentMode) {
                if (currentMode == PullToRefreshBase.Mode.PULL_FROM_START) {
                    refreshView.getRefreshableView().reload();
                }

            }
        });
        if (StringUtil.isNotEmpty(url) && (url.indexOf("wScratch") > 0)) {
            mPullRefreshWebView.setMode(PullToRefreshBase.Mode.DISABLED);
        }
    }

    @Override
    protected void onPause() {
        try {
            ((YunloanApp) getApplicationContext()).forceUnregisterComponentCallbacks();
        } catch (Exception e) {
            //unregister error
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (simpleAlertDialog != null) {
            if (simpleAlertDialog.isShowing()) {
                simpleAlertDialog.dismiss();
            }
            simpleAlertDialog = null;
        }

        if (webpageView != null) {

            webpageView.stopLoading();
            webpageView.loadData("", "text/html", "utf-8");
            webpageView.reload();

            webpageView.setWebChromeClient(null);
            webpageView.setWebViewClient(null);

            ViewGroup parent = (ViewGroup) webpageView.getParent();
            if (parent != null) {
                parent.removeView(webpageView);
            }

            webpageView.destroy();
            webpageView = null;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            if (webpageView.canGoBack()) {
                goBack();
                return true;
            } else {
                finish();
                return true;
            }
        }
        return false;
    }

    public static void showActivity(Context mContext, String mUrl) {
        if (StringUtil.isEmpty(mUrl)) {
            ToastMaker.showToastLong(R.string.invalidate_link);
            return;
        }
        Bundle extBundle = new Bundle();
        extBundle.putString(INTENTURL, mUrl);
        showActivity(mContext, extBundle);
    }


    public static void showActivity4Ad(Context mContext, String mUrl, String secondUrl) {
        Bundle extBundle = new Bundle();
        extBundle.putString(BUNDLE_EXTRA_AD, secondUrl);
        extBundle.putString(INTENTURL, mUrl);
        showActivity(mContext, extBundle);
    }

    private static void showActivity(Context mContext, Bundle bundle) {
        if (mContext == null) return;
        Intent intent = new Intent(mContext, BrowserActivity.class);
        intent.putExtras(bundle);
        mContext.startActivity(intent);
    }
}
